package ui.magic.magiclibs.container.Tool;

import java.util.Vector;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by liushiyin on 17-10-12.
 */

public class Timer extends Thread {

    private Vector<TimerInfo> timerInfos=new Vector<>();
    private boolean isExit;
    private TimerObserver observer=null;
    private Lock lock=new ReentrantLock();

    public boolean setTimerTimerObserver(TimerObserver observer){
        this.observer=observer;
        return (this.observer!=null);
    }

    public Timer(){
        start();
    }

    @Override
    public void run() {
        while(true){
            if(isExit){
                break;
            }
            checkDelTimer();
            long curTime=System.currentTimeMillis();
            lock.lock();
            for (TimerInfo info:timerInfos) {
                info.setCurTime(curTime);
                if(info.checkExecute()){
                    if(observer!=null)
                    try{
                        observer.OnTimer(info.getId(),info.getDescribe());
                    }catch (Exception e){
                        return;
                    }
                    info.setLastTime(curTime);
                }
            }
            lock.unlock();
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void exitTimer()
    {
        isExit=true;
    }

    //添加定时器
    //@Param id:定时器id
    //@Param delay:定时器延时
    //@Param describe:定时器描述
    //@return boolean:添加成功返回true,失败返回false
    public boolean addTimer(int id,int delay,String describe){
        TimerInfo info=new TimerInfo(id,delay,System.currentTimeMillis(),describe);
        lock.lock();
        boolean bRet=timerInfos.add(info);
        lock.unlock();
        return bRet;
    }

    //删除定时器
    //@Param id:定时器id
    public void removeTimer(long id){
        for (TimerInfo info:timerInfos
             ) {
            if(info.getId()==id){
                info.setDel();
            }
        }
    }

    //检查并删除应该删除的定时器
    private void checkDelTimer(){
       for (int i=0;i<timerInfos.size();){
           if(timerInfos.get(i).isDel()){
               timerInfos.remove(i);
           }else{
               ++i;
           }
       }
    }
}
